import { WorkBook, WorkSheet } from "xlsx/types";
import xlsx from 'xlsx';
import { UploadFile } from "antd/lib/upload/interface";

export function parseFileToWorkbook(file: Blob, sheetName: string | number | (string | number)[] | undefined): Promise<WorkBook> {
    return new Promise<WorkBook>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            if (e.target !== null) {
                const workbook = xlsx.read(e.target.result, {
                    type: 'binary',
                    sheets: sheetName
                });
                resolve(workbook);
            } else {
                reject();
            }
        };
        reader.onerror = reject;
        reader.readAsBinaryString(file);
    });
}

export function parseFileToSheetJson<T = string>(file: UploadFile, sheetName: string | number = 0): Promise<T[][]> {
    return new Promise((resolve, reject) => {
        if (file.originFileObj !== undefined) {
            parseFileToWorkbook(file.originFileObj, sheetName).then((workbook) => {
                let sheet;
                if (typeof sheetName === 'string') {
                    sheet = workbook.Sheets[sheetName];
                } else if (typeof sheetName === 'number') {
                    sheet = workbook.Sheets[workbook.SheetNames[sheetName]]
                } else {
                    reject(`文件 《${file.name}》中未找到名称为《${sheetName}》的表，请检查你的数据表数据和格式是否正确。`);
                }
                if (sheet !== undefined) {
                    const sheetJson = sheetToJson<T>(sheet);
                    resolve(sheetJson);
                } else {
                    reject(`文件《${file.name}》中未找到名称为《${sheetName}》的表，请检查你的数据表数据和格式是否正确。`);
                }
            }, reject);
        } else {
            reject(`《${file.name}》是无效的考勤记录文件，请严格按照格式要求上传数据和格式正确的文件。`);
        }
    });
}

export function sheetToJson<T = string>(sheet: WorkSheet) {
    return xlsx.utils.sheet_to_json<T[]>(sheet, { blankrows: true, header: 1, defval: '' });
}

